package models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import play.data.validation.Required;
import siena.Filter;
import siena.Query;

public class IdeaRequest extends AbstractActivity {
	@Required public String description;
	
	@Filter("ideaRequest")
	public Query<IdeaUnit> ideas;
	
	public static Query<IdeaRequest> all() {
		return all(IdeaRequest.class);
	}
	
	public static IdeaRequest findById(Long id) {
		return all().filter("id", id).get();
	}
	
	public static List<IdeaRequest> findAllOpen(Date date, Query<IdeaRequest> query) {
		if(query != null) query = query.filter("start<", date);
		else query = all().filter("start<", date);
				
		return filterByEndDate(query.fetch(), date, true);
	}
	
	public static List<IdeaRequest> findAllClose(Date date, Query<IdeaRequest> query) {
		if(query != null) query = query.filter("start<", date);
		else query = all().filter("start<", date);
		
		return filterByEndDate(query.fetch(), date, false);
	}
	
	public static List<IdeaRequest> findAllRemaining(Date date, Query<IdeaRequest> query) {
		List<IdeaRequest> ideaRequests = null;
		if(query != null) ideaRequests = query.filter("start>", date).fetch();
		else ideaRequests = all().filter("start>", date).fetch();
		
		return filterByEndDate(ideaRequests, date, true);
	}
	
	public static List<IdeaRequest> findByStartDate(Date startDate, Date endDate, Query<IdeaRequest> query) {
		List<IdeaRequest> ideaRequests = null;
		if(query == null) query = all();
		ideaRequests =  query.filter("start>=", startDate).filter("start<=", endDate).fetch();
		
		return ideaRequests;
	}
	
	public static List<IdeaRequest> findByEndDate(Date startDate, Date endDate, Query<IdeaRequest> query) {
		List<IdeaRequest> ideaRequests = null;
		if(query == null) query = all();
		ideaRequests = query.filter("end>=", startDate).filter("end<=", endDate).fetch();
		
		return ideaRequests;
	}

	
	/**
	 * Manual filter by the ending fate. Because now datastore don't allow inequality filters on more than one property.
	 * @param list 
	 * @param end
	 * @param flag Indicates if the end date has to be greater (true) than the incoming date o lower (false).
	 * @return
	 */
	private static  List<IdeaRequest> filterByEndDate(List<IdeaRequest> list, Date date, boolean flag) {
		ArrayList<IdeaRequest> result = new ArrayList<IdeaRequest>();
		if(list != null) {
			for(IdeaRequest ir : list) {
				if(flag) {
					if(ir.end.getTime() >= date.getTime()) result.add(ir);
				} else {
					if(ir.end.getTime() <= date.getTime()) result.add(ir);
				}
				
			}
		}
		
		return result;
	}
}
